package com.example.rdcproject.ving.notes.view.User;

import com.example.rdcproject.ving.notes.entity.User;
import com.example.rdcproject.ving.notes.service.ConnectionPool;
import com.example.rdcproject.ving.notes.util.DBUtils;
import com.example.rdcproject.ving.notes.util.NumberInputVerifier;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class PersonnalInfoView extends JFrame {
      User user = User.getInstance();

    private final JLabel birthdateLabel = new JLabel("生日日期(yyyy-MM-dd)：");
    private final JLabel planLabel = new JLabel("每日计划(数字)：");
    JToggleButton privateButton = new JToggleButton("私密状态");

    private final JLabel birthdateValueLabel = new JLabel("");
    private final JLabel planValueLabel = new JLabel("");


    private final JTextField birthdateField = new JTextField(20);
    private final JTextField planField = new JTextField(3);


    public PersonnalInfoView() {
        // 创建面板
        JPanel panel = new JPanel(new GridLayout(4, 2));

        ConnectionPool connectionPool = null;
        Connection connection = null;
        PreparedStatement statement = null;

        try {
            connectionPool = ConnectionPool.getInstance();
            connection = connectionPool.getConnection();

            // 开始事务
            connection.setAutoCommit(false);

            String nickname = user.getNickname();
            //定义sql语句
            String sql = "select user_birthdate ,user_dailyGoal from user where user_nickname = ?";
            statement = connection.prepareStatement(sql);
            statement.setString(1, nickname);

            ResultSet rs = statement.executeQuery();
            while (rs.next()) {
                birthdateValueLabel.setText(rs.getString(1));
                planValueLabel.setText(rs.getString(2));
            }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            assert connectionPool != null;
            connectionPool.releaseConnection(connection);
            try {
                DBUtils.close(statement);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        // 添加组件到面板
        panel.add(birthdateLabel);
        panel.add(birthdateValueLabel);
        panel.add(planLabel);
        panel.add(planValueLabel);
        panel.add(privateButton);
        // 创建编辑按钮
        JButton editButton = new JButton("编辑");

        // 添加编辑按钮的事件处理
        editButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 切换到编辑面板
                getContentPane().remove(panel);
                getContentPane().add(editPanel());
                getContentPane().validate();
            }
        });

        // 将编辑按钮添加到面板
        panel.add(editButton);

        // 添加面板到窗口
        getContentPane().add(panel);

        // 设置窗口的标题和大小
        setTitle("个人信息");
        setSize(400, 200);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setLocationRelativeTo(null);
    }

    private JPanel editPanel() {

        //定义日期格式
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        // 创建面板
        JPanel panel = new JPanel(new GridLayout(4, 2));

        // 添加组件到面板
        panel.add(new JLabel("生日日期(yyyy-MM-dd)："));
        panel.add(birthdateField);
        panel.add(new JLabel("每日计划："));
        panel.add(planField);


        // 创建保存按钮
        JButton saveButton = new JButton("保存");

        // 添加保存按钮的事件处理
        saveButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                //获取输入日期
                String birthdateStr =birthdateField.getText();

                //通过限制器数字
                planField.setInputVerifier(new NumberInputVerifier());

                try {
                    Date birthdate = dateFormat.parse(birthdateStr);

                    //将日期格式化
                    String formatterBirhthdate = dateFormat.format(birthdate);

                    //添加到标签
                    birthdateValueLabel.setText(formatterBirhthdate);
                    user.setBirthdate(formatterBirhthdate);
                } catch (ParseException ex) {
                    System.out.println("你输入的日期格式有误！");
                }

                int  goal = Integer.parseInt(planField.getText());
                planValueLabel.setText(planField.getText());
                user.setDailyGoal(goal);

                user.setPrivate(privateButton.isSelected());
                try {
                    updateInfo(user.getBirthdate(), user.getDailyGoal(), user.isPrivate());
                } catch (SQLException ex) {
                    ex.printStackTrace();
                    System.out.println("数据库存储失败！");
                }
                // 切换到个人信息面板
                getContentPane().remove(panel);
                getContentPane().add(createInfoPanel());
                getContentPane().validate();
            }
        });

        // 将保存按钮添加到面板
        panel.add(saveButton);

        return panel;
    }
        private JPanel createInfoPanel() {
            // 创建面板
            JPanel panel = new JPanel(new GridLayout(4, 2));

            ConnectionPool connectionPool = null;
            Connection connection = null;
            PreparedStatement statement = null;

            try {
                connectionPool = ConnectionPool.getInstance();
                connection = connectionPool.getConnection();

                // 开始事务
                connection.setAutoCommit(false);

                String nickname = user.getNickname();
                //定义sql语句
                String sql = "select user_birthdate ,user_dailyGoal from user where user_nickname = ?";
                statement = connection.prepareStatement(sql);
                statement.setString(1, nickname);

                ResultSet rs = statement.executeQuery();
                while (rs.next()) {
                    birthdateValueLabel.setText(rs.getString(1));
                    planValueLabel.setText(rs.getString(2));
                }

            }catch (Exception e){
                e.printStackTrace();
            }finally {
                assert connectionPool != null;
                connectionPool.releaseConnection(connection);
                try {
                    DBUtils.close(statement);
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            // 组件到面板
            panel.add(birthdateLabel);
            panel.add(birthdateValueLabel);
            panel.add(planLabel);
            panel.add(planValueLabel);

            // 创建编辑按钮
            JButton editButton = new JButton("编辑");

            // 添加编辑按钮的事件处理
            editButton.addActionListener(e -> {
                // 切换到编辑面板
                getContentPane().remove(panel);
                getContentPane().add(editPanel());
                getContentPane().validate();
            });

            // 将编辑按钮添加到面板
            panel.add(editButton);

            return panel;
        }

     //对个人信息进行更新
    private void updateInfo(String birthday, int dailyGoal, Boolean isPrivate) throws SQLException {
           String account = user.getNickname();

        ConnectionPool connectionPool = null;
        Connection connection = null;
        PreparedStatement statement = null;
          try {
              connectionPool = ConnectionPool.getInstance();
              connection = connectionPool.getConnection();

              // 开始事务
              connection.setAutoCommit(false);

              //定义sql语句
              String sql = "update user set user_birthdate=?, user_dailyGoal=?, user_isPrivate=? where user_nickname = ?";
              statement = connection.prepareStatement(sql);

              statement.setString(1, birthday);
              statement.setInt(2, dailyGoal);
              statement.setBoolean(3, isPrivate);
              statement.setString(4,account);

              statement.executeUpdate();

              // 提交事务
              connection.commit();

          }catch (Exception e){
              e.printStackTrace();
              // 处理SQL异常，回滚事务
              connection.rollback();
          }finally {
              assert connectionPool != null;
              connectionPool.releaseConnection(connection);
              DBUtils.close(statement);
          }
    }

}
